import requests
from bs4 import BeautifulSoup
import time
from urllib.parse import quote

def get_baidu_hot_search(top_n=5):
    """
    获取百度热搜前N条标题
    
    参数:
        top_n (int): 需要获取的热搜数量，默认为5
        
    返回:
        list: 包含热搜标题的列表
    """
    # 设置请求头，模拟浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Referer': 'https://www.baidu.com/'
    }
    
    try:
        # 构造百度热搜URL（使用移动端页面更简单）
        url = "https://top.baidu.com/board?tab=realtime"
        
        # 发送请求，设置超时时间
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查请求是否成功
        
        # 解析HTML内容
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 查找热搜标题 - 根据实际页面结构调整选择器
        titles = []
        items = soup.select('.container-bg_lQ801 .content_1YWBm a')
        
        for i, item in enumerate(items[:top_n]):
            title = item.text.strip()
            titles.append(title)
            print(f"{i+1}. {title}")
            
            # 礼貌性延迟，避免对服务器造成压力
            time.sleep(0.5)
            
        return titles
    
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
        return []
    except Exception as e:
        print(f"解析出错: {e}")
        return []

if __name__ == "__main__":
    print("百度实时热搜前5条:")
    get_baidu_hot_search(5)
import requests
from bs4 import BeautifulSoup
import time
from urllib.parse import quote

def get_baidu_hot_search(top_n=5):
    """
    获取百度热搜前N条标题
    
    参数:
        top_n (int): 需要获取的热搜数量，默认为5
        
    返回:
        list: 包含热搜标题的列表
    """
    # 设置请求头，模拟浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Referer': 'https://www.baidu.com/'
    }
    
    try:
        # 构造百度热搜URL（使用移动端页面更简单）
        url = "https://top.baidu.com/board?tab=realtime"
        
        # 发送请求，设置超时时间
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查请求是否成功
        
        # 解析HTML内容
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 查找热搜标题 - 根据实际页面结构调整选择器
        titles = []
        items = soup.select('.container-bg_lQ801 .content_1YWBm a')
        
        for i, item in enumerate(items[:top_n]):
            title = item.text.strip()
            titles.append(title)
            print(f"{i+1}. {title}")
            
            # 礼貌性延迟，避免对服务器造成压力
            time.sleep(0.5)
            
        return titles
    
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
        return []
    except Exception as e:
        print(f"解析出错: {e}")
        return []

if __name__ == "__main__":
    print("百度实时热搜前5条:")
    get_baidu_hot_search(5)
import requests
from bs4 import BeautifulSoup
import time
from urllib.parse import quote

def get_baidu_hot_search(top_n=5):
    """
    获取百度热搜前N条标题
    
    参数:
        top_n (int): 需要获取的热搜数量，默认为5
        
    返回:
        list: 包含热搜标题的列表
    """
    # 设置请求头，模拟浏览器访问
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Referer': 'https://www.baidu.com/'
    }
    
    try:
        # 构造百度热搜URL（使用移动端页面更简单）
        url = "https://top.baidu.com/board?tab=realtime"
        
        # 发送请求，设置超时时间
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()  # 检查请求是否成功
        
        # 解析HTML内容
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # 查找热搜标题 - 根据实际页面结构调整选择器
        titles = []
        items = soup.select('.container-bg_lQ801 .content_1YWBm a')
        
        for i, item in enumerate(items[:top_n]):
            title = item.text.strip()
            titles.append(title)
            print(f"{i+1}. {title}")
            
            # 礼貌性延迟，避免对服务器造成压力
            time.sleep(0.5)
            
        return titles
    
    except requests.exceptions.RequestException as e:
        print(f"请求出错: {e}")
        return []
    except Exception as e:
        print(f"解析出错: {e}")
        return []

if __name__ == "__main__":
    print("百度实时热搜前5条:")
    get_baidu_hot_search(5)
